<?php
/**
 * alltosun.com  index.php
 * ============================================================================
 * 版权所有 (C) 2009-2013 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 王德康 (wangdk@alltosun.com) $
 * $Date: 2016-3-11 上午11:03:50 $
 * $Id$
 */
class DownloadExcel
{

    /**
     * 获取二维数组中最大的数组，返回key
     * @param unknown_type $info
     * @param unknown_type $col_content_arr
     * @return Ambigous <>
     */
    private static function get_max_result($info,$col_content_arr)
    {
        $data = array(0);
        if ($col_content_arr) {
            foreach ($col_content_arr as $v) {
                $data[$v] = count($info[$v]);
            }
            rsort($data);
        }

        return $data[0];
    }


    /**
     * 导出单行中的数据列表
     * @param unknown_type $objActSheet         PHPExcel对象
     * @param unknown_type $info                当前行的数据
     * @param unknown_type $select_field_name   当前选中的字段
     * @param unknown_type $multi_filed_arr     多行字段数组
     * @param unknown_type $multi_filed_arr_key 多行字段数据对应的数据的KEY
     * @param unknown_type $line                当前行数
     * @param unknown_type $cell_flag           当前行Excel标示符 A1, A2
     */
    private static function write_multi_data($objActSheet,$info, $select_field_name, $multi_filed_arr,$multi_filed_arr_key, $line, $cell_flag)
    {
        foreach ($multi_filed_arr as $field_name) {

            // 需要合并的单元格
            if ($select_field_name == $field_name) {
                foreach ($info[$field_name] as $sub_k => $sub_info) {

                    // 自增行
                    $title = $cell_flag.($sub_k + $line);
                    $objActSheet->setCellValue($title, $sub_info[$multi_filed_arr_key[$field_name]]);
                }
            }
        }
    }

    /**
     *
     * @param unknown_type $objActSheet          PHPExcel对象
     * @param unknown_type $info                 当前行的数据
     * @param unknown_type $select_field_name    当前选中的字段
     * @param unknown_type $cell_title           当前要写入的单元格标示符
     * @param unknown_type $count                最大多行的数量
     * @param unknown_type $line                 当前行数
     * @param unknown_type $cell_flag            当前行Excel标示符 A1, A2，组织要合并的单元格
     */
    private static function write_data($objActSheet, $info,  $select_field_name, $cell_title, $count, $line, $cell_flag )
    {
        $value = $info[$select_field_name];
        $objActSheet->setCellValue($cell_title, $value);

        if ($count > 1) {
            $objActSheet->getStyle($cell_title)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

            $start = $cell_flag.$line;
            $end   = $cell_flag.($line + $count - 1);
            $objActSheet->mergeCells($start.':'.$end);
        }
    }

    /**
     * 设置下载header
     * @param unknown_type $objWriter   PHPExcel对象
     * @param unknown_type $works_title 下载的Title
     */
    private static function set_download_header($objWriter, $works_title)
    {

        // 设置页面类型
        header("Content-Type: application/vnd.ms-excel");

        // 用于下载的文件头
        header("Content-Type: application/force-download");
        header("Content-Type: application/download");
        header("Content-Type: application/octet-stream");


        $title = trim($works_title).".xls";

        // ff正常，ie不正常，下面是从网站找到的解决方案
        if (preg_match('/MSIE/',$_SERVER['HTTP_USER_AGENT'])) {
            $title = rawurlencode($title);
        }

        header("Content-Disposition: attachment; filename=".$title);
        header("Content-Transfer-Encoding: binary");

        // 最后修改时间
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        // 不使用缓存
        header('Cache-Control: ust-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: public');
        header("Expires: 0");
        header("Pragma: public");
        $objWriter->save('php://output');
    }

    /**
     * 设置文档属性，第一行标题
     * @param unknown_type $objActSheet
     * @param unknown_type $objPHPExcel
     * @param unknown_type $col_arr
     * @param unknown_type $col_title_arr
     */
    private static function set_doc_attr($objActSheet, $objPHPExcel, $col_arr, $col_title_arr)
    {
        // 设置文档属性
        foreach ($col_arr as $k => $v) {

            // 设置4个列的宽度
            $objActSheet->getColumnDimension($v)->setWidth(20);
            $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(30);

            // 设置单位格内容A1,B1,C1,D1
            $col_title_arr[$k] = $col_title_arr[$k];
            $objActSheet->setCellValue($v."1", $col_title_arr[$k]);

            // 格式化数字为字符串，避免导致数字默认右对齐单元格
            $objActSheet->getStyle($v."1")->getNumberFormat()->setFormatCode("@");
        }
    }

    public static function download_excel($works_title, $dealers_list,  $col_title_arr, $col_content_keys, $multi_filed_arr, $multi_filed_arr_key)
    {

        $objPHPExcel = new PHPExcel();
        $objWriter   = new PHPExcel_Writer_Excel5($objPHPExcel);

        //设置当前的sheet索引，用于后续的内容操纵
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();
        $objActSheet->setTitle($works_title);

        $title_count = count($col_title_arr);
        if ( $title_count != count($col_content_keys)) {
            return '标题和键值不匹配!';
        }

        //  列 $col_arr = array('A', 'B', 'C', 'D', 'F', 'E', 'H', 'I', 'J');
        if ($title_count- 1 > 32) {
            return '超过最大列';
        }

        $col_arr = array_map("chr", range(65, 65 + $title_count - 1));

        // 设置文档属性
        self::set_doc_attr($objActSheet, $objPHPExcel, $col_arr, $col_title_arr);

        // 单元个默认从1开始
        $setup = 2;

        foreach($dealers_list as $k=>$v) {
            $key = $k + $setup;

            // 获取最大行数，合并单元格
            $count = self::get_max_result($v, $multi_filed_arr);
            foreach ($col_content_keys as $sk => $val) {

                // 单元格标识
                $title = $col_arr[$sk].$key;

                // 格式化数字为字符串，避免导致数字默认右对齐单元格
                $objActSheet->getStyle($title)->getNumberFormat()->setFormatCode("@");

                if (in_array($val, $multi_filed_arr)) {
                    self::write_multi_data($objActSheet, $v, $val, $multi_filed_arr, $multi_filed_arr_key, $key, $col_arr[$sk]);
                }else {
                    self::write_data($objActSheet, $v, $val, $title, $count, $key, $col_arr[$sk]);
                }
            }
            if ($count) $setup = $setup + $count - 1;
        }

        self::set_download_header($objWriter, $works_title);
        exit;
    }
}

class Action
{
    
    /**
     * 查看合伙人库存信息
     */
    public function show_dealer_store_goods_list()
    {
        // 将合伙人库存信息缓存
        global $mc_wr;
        $key = 'dealer_store_goods_list';
        $store_goods_data = $mc_wr->get($key);
        if ($store_goods_data) {
            // 有缓存则返回
            $store_goods_list = json_decode($store_goods_data, true);
        } else {
            $dealers_ids = _model('user')->getFields('id', array('`dealer_level` > '=>0, 'status'=>1, 'is_enable'=>1));
            $store_goods_list = array();
            if ($dealers_ids) {
                foreach ($dealers_ids as $k=>$v) {
                    $store_goods_info = _model('store_goods_sku')->getAll('select sum(`stock`) as `all_stock`,`user_id` from `store_goods_sku` WHERE `user_id`='.$v);
                    if (isset($store_goods_info[0]['all_stock'])) {
                        $store_goods_list[$v] = $store_goods_info[0]['all_stock'];
                    } else {
                        $store_goods_list[$v] = 0;
                    }
            
                }
                arsort($store_goods_list);
                $store_goods_data = json_encode($store_goods_list);
                $mc_wr->set($key, $store_goods_data, 60 * 60 * 3);
            } else {
                // 说明没有合伙人@TODO
            }
        }
        
        $list = array();
        foreach ($store_goods_list as $k => $v) {
            $dealer_info    = user_helper::get_user_info($k);
            if (!$dealer_info) {
                continue;
            }
            $dealer_address = dealers_helper::get_default_dealer_address($k);
            $list[$k]['id'] = $k;
            $list[$k]['all_stock'] = $v;
            $list[$k]['dealer_address'] = @$dealer_address['dealer_address'] ? $dealer_address['dealer_address'] : '暂无';
            $list[$k]['bbcoin'] = $dealer_info['bbcoin'];
            $list[$k]['realname'] = @$dealer_info['realname'] ? @$dealer_info['realname'] : @$dealer_info['nickname'];
        }
        
        Response::assign('list', $list);
        Response::display('admin/show_dealer_store_goods_list.html');
    }
    
    
    

    /**
     * 查看线上所有的经销商仓库地址
     */
    public function get_dealer_address_list()
    {
//         $data_list = _model('dealer_address')->getList(array(1=>1));
//         echo '<pre>';
//         print_r($data_list);
    }
    
    /**
     * 找回经销商默认仓库地址
     * @return Ambigous <string, multitype:, NULL, mixed, multitype:Ambigous <multitype:, NULL> , array(), unknown>
     */
    public function back_dealer_address()
    {
//         $dealer_ids = user_helper::get_role_user_ids(user_config::AGENCY, '');
//         if ($dealer_ids) {
//             foreach ($dealer_ids as $k=>$v) {
//                 $dealer_address = _uri('dealer_address', array('user_id'=>$v, 'is_default'=>1));
//                 $user_info = user_helper::get_user_info($v);
//                 if (!$user_info) {
//                     continue;
//                 }
//                 if (!$dealer_address) {
                    
//                     $area_tree_info = _widget('area')->get_area_info_by_area_code($user_info['area_code']);
//                     $dealer_address_info = array();
                    
//                     if (isset($area_tree_info['county_info'])) {
//                         $dealer_address_info['county_code']   = $area_tree_info['county_info']['area_code'];
//                         $dealer_address_info['city_code']     = $area_tree_info['city_info']['area_code'];
//                         $dealer_address_info['province_code'] = $area_tree_info['province_info']['area_code'];
                    
//                     } elseif (isset($area_tree_info['city_info'])) {
//                         $dealer_address_info['city_code']     = $area_tree_info['city_info']['area_code'];
//                         $dealer_address_info['province_code'] = $area_tree_info['province_info']['area_code'];
                    
//                     } elseif (isset($area_tree_info['province_info'])) {
//                         $dealer_address_info['province_code'] = $area_tree_info['province_info']['area_code'];
//                     }
                    
//                     $dealer_address_info['is_default']     = 1;
//                     $dealer_address_info['add_time']       = date('Y-m-d H:i:s');
//                     $dealer_address_info['update_time']    = date('Y-m-d H:i:s');
//                     $dealer_address_info['dealer_address'] = $user_info['store_house'];
//                     $dealer_address_info['user_id']        = $v;
//                     $dealer_address_info['dealer_name']    = @$user_info['realname'] ? $user_info['realname'] : $user_info['nickname'];
//                     $dealer_address_info['dealer_mobile']  = $user_info['mobile'];
                    
//                     _model('dealer_address')->create($dealer_address_info);
//                 }
                
//                 usleep(10000);
                
//                 $address_list = _model('dealer_address')->getList(array('user_id'=>$v));
//                 if ($address_list) {
//                     foreach ($address_list as $key => $val) {
//                         // 更新默认地址的收货人姓名和手机号
//                         $dealer_name = @$user_info['realname'] ? $user_info['realname'] : $user_info['nickname'];
//                         $dealer_mobile = $user_info['mobile'];
//                         if (!$val['dealer_name'] || !$val['dealer_mobile']) {
//                             _model('dealer_address')->update($val['id'], array('dealer_name'=>$dealer_name, 'dealer_mobile'=>$dealer_mobile));
//                         }
                        
//                     }
                    
//                 }
                
//             }
//         }
    }
    
    private function load_data()
    {
        $filter['dealer_level >'] = 0;
        $filter['is_enable'] = 1;

        $dealers_list = _model('user')->getList($filter);
        if ($dealers_list) {
            foreach ($dealers_list as $k => $v) {

                // 旗下员工列表
                $dealers_list[$k]['market_user_list'] = dealers_helper::get_dealers_staff_list($v['id']);

                // 门店列表
                $dealers_list[$k]['store_list']       = store_helper::get_dealers_store_list($v['id']);

                // 订单数量
                $dealers_list[$k]['order_list']       = order_helper::get_dealers_order_list($v['id']);
                $dealers_list[$k]['order_count'] = count($dealers_list[$k]['order_list']);


                // 订单数量
                $dealers_list[$k]['store_order_list'] = order_helper::get_dealers_store_order_list($v['id']);
                $dealers_list[$k]['store_order_count'] = count($dealers_list[$k]['store_order_list']);;

                // 上级经销商
                $dealers_list[$k]['dealer_title']     = '一级经销商';
                $dealers_list[$k]['parent_name']     = '';
                if ($v['parent_id'])  {
                    $dealers_list[$k]['dealer_title']     = '二级经销商';

                    $dealers_list[$k]['parent_info']      = user_helper::get_user_info($v['parent_id']);
                    $dealers_list[$k]['parent_name']      = $dealers_list[$k]['parent_info']['realname'];

                }

            }
        }

        return $dealers_list;
    }

    public function index()
    {

        $dealers_list = $this->load_data();
        Response::assign('dealers_list', $dealers_list);

        Response::display('admin/dealers_list.html');
    }

    public function export()
    {

        $dealers_list = $this->load_data();

        // 第一排的标题
        $col_title_arr   = array('姓名', '电话', '签约门店', '旗下员工', '总部订单数量', '门店订单数量', '类型', '上级经销商', '添加时间');

        // 单元格中的内容，这些是works_list中的字段
        $col_content_arr = array('realname', 'mobile', 'store_list','market_user_list', 'order_count','store_order_count', 'dealer_title', 'parent_name', 'add_time');

        $down_filename = 'download';

        $multi_filed_arr = array('market_user_list', 'store_list');
        $multi_filed_arr_key = array('market_user_list'=>'realname', 'store_list'=>'title');
        DownloadExcel::download_excel($down_filename, $dealers_list, $col_title_arr, $col_content_arr, $multi_filed_arr, $multi_filed_arr_key);
    }

}